package com.acmedcare.framework.exchange.center.core.adapter;

import com.acmedcare.framework.exchange.center.core.exception.DeprecatedAdapterException;
import com.acmedcare.framework.exchange.center.core.PluginMetadata;
import com.acmedcare.framework.exchange.center.core.metadata.AdapterMapping;
import com.acmedcare.framework.exchange.center.core.metadata.IDataAdapter;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import lombok.extern.slf4j.Slf4j;
import xyz.vopen.cartier.classpathscanner.scanner.ScanResult;

@Slf4j
@SuppressWarnings("unused")
public class DefaultAdapterResolver implements IAdapterResolver {

  @Override
  public void resolve(ConcurrentHashMap<String, AdapterMetadata> adapterMetadata,
      PluginMetadata metadata) {
    try {

      ScanResult result = metadata.getScanResult();
      ClassLoader classLoader = metadata.getClassLoader();
      List<String> adapterNames = result.getNamesOfClassesImplementing(IDataAdapter.class);
      if (!adapterNames.isEmpty()) {
        adapterNames.forEach((name) -> {

          AdapterMetadata adapter = new AdapterMetadata();
          String adapterName;
          try {

            Class<?> adapterClass = classLoader.loadClass(name);
            adapter.setAdapterClass(adapterClass);

            AdapterMapping mapping = adapterClass.getAnnotation(AdapterMapping.class);
            if (mapping != null) {

              adapterName = mapping.value();
            } else {

              adapterName = adapterClass.getSimpleName();
            }

            adapterName = adapterName.toLowerCase().trim();
            AdapterMetadata obj = adapterMetadata.get(adapterName);
            if (obj != null) {

              throw new DeprecatedAdapterException();
            }

            adapter.setPath(metadata.getJarPath());
            adapterMetadata.put(adapterName, adapter);
          } catch (Exception e) {

            log.error("插件加载失败，插件名称:" + metadata.getName(), e);
          }
        });
      }
    } catch (Exception e) {

      log.error("插件加载失败，插件名称:" + metadata.getName(), e);
    }
  }
}
